package bbs.controller;

import bbs.annotation.GlobalInterceptor;
import bbs.annotation.VerifyParam;
import bbs.controller.base.ABaseController;
import bbs.entity.config.WebConfig;
import bbs.entity.constants.Constants;
import bbs.entity.enums.ResponseCodeEnum;
import bbs.entity.enums.UserOperFrequencyTypeEnum;
import bbs.entity.vo.ResponseVO;
import bbs.exception.BusinessException;
import bbs.utils.StringTools;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.HashMap;

@RestController("fileController")
@RequestMapping({"/file"})
public class FileController extends ABaseController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Resource
    private WebConfig webConfig;
    /**
     * 获取头像
     * @param response
     * @param userId
     */
    @RequestMapping({"/getAvatar/{userId}"})
    @GlobalInterceptor(checkLogin = false, checkParams = true)
    public void getAvatar(HttpServletResponse response, @VerifyParam(required = true) @PathVariable("userId") String userId) {
        String avatarFolderName = Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_AVATAR_NAME;
        String avatarPath = this.webConfig.getProjectFolder() + avatarFolderName + userId + Constants.AVATAR_SUFFIX;
        File avatarFolder = new File(avatarFolderName);
        if (!avatarFolder.exists()) avatarFolder.mkdirs();

        File file = new File(avatarPath);
        String imageName = userId + Constants.AVATAR_SUFFIX;
        if(!file.exists()) imageName = Constants.AVATAR_DEFAULT;
        readImage(response, Constants.FILE_FOLDER_AVATAR_NAME, imageName);
    }


    @RequestMapping({"/getImage/{imageFolder}/{imageName}"})
    public void getImage(HttpServletResponse response, @PathVariable("imageFolder") String imageFolder, @PathVariable("imageName") String imageName) {
        readImage(response, imageFolder, imageName);
    }

    private void readImage(HttpServletResponse paramHttpServletResponse, String paramString1, String paramString2) {
        ServletOutputStream servletOutputStream = null;
        FileInputStream fileInputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            if (StringTools.isEmpty(paramString1) || StringUtils.isBlank(paramString2))
                return;
            String imageSuffix = StringTools.getFileSuffix(paramString2);
            String filePath = this.webConfig.getProjectFolder() + "/file/" + "images/" + paramString1 + "/" + paramString2;
            if ("temp".equals(paramString1)) {
                filePath = this.webConfig.getProjectFolder() + "/file/" + paramString1 + "/" + paramString2;
            } else if (paramString1.contains("avatar/")) {
                filePath = this.webConfig.getProjectFolder() + "/file/" + paramString1 + paramString2;
            }
            File file = new File(filePath);
            if (!file.exists())
                return;
            imageSuffix = imageSuffix.replace(".", "");
            if (!"avatar/".equals(paramString1))
                paramHttpServletResponse.setHeader("Cache-Control", "max-age=2592000");
            paramHttpServletResponse.setContentType("image/" + imageSuffix);
            fileInputStream = new FileInputStream(file);
            servletOutputStream = paramHttpServletResponse.getOutputStream();
            byteArrayOutputStream = new ByteArrayOutputStream();
            int i = 0;
            while (-1 != (i = fileInputStream.read()))
                byteArrayOutputStream.write(i);
            servletOutputStream.write(byteArrayOutputStream.toByteArray());
        } catch (Exception exception) {
            logger.error("图片读取异常", exception);
        } finally {
            if (byteArrayOutputStream != null)
                try {
                    byteArrayOutputStream.close();
                } catch (IOException iOException) {
                    iOException.printStackTrace();
                }
            if (servletOutputStream != null)
                try {
                    servletOutputStream.close();
                } catch (IOException iOException) {
                    logger.error("IO异常", iOException);
                }
            if (fileInputStream != null)
                try {
                    fileInputStream.close();
                } catch (IOException iOException) {
                    logger.error("IO异常", iOException);
                }
        }
    }
}
